import 'package:flutter/material.dart';
import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'dart:convert' as Convert;

/// 项目里有个大坑，在加Expanded的时候一定要限制高，因为如果不限制高的话，就会出现无法适应的情况
/// 切记！！！
/// 出现了一些小问题，貌似和cpu架构有关系，在手机安装后无法正常运行

class MovieView extends StatefulWidget {
  @override
  _MovieViewState createState() => _MovieViewState();
}

class _MovieViewState extends State<MovieView> {
  Set likedSet = Set();

  var subjects = [];

  //网络请求获取信息
  requestInfo() async {
    var httpClient = HttpClient();
    var uri = Uri.http(
        'douban.uieee.com', '/v2/movie/top250', {'start': '0', 'count': '150'});
    var req = await httpClient.getUrl(uri);
    var res = await req.close();
//    FutureBuilder(
//      future: DefaultAssetBundle.of(context).loadString('assets/test.json'),
//      builder: (context, snap){
//        Map res = Convert.jsonDecode(snap.data.toString());
//        setState(() {
//          subjects = res['subjects'];
//        });
//        return null;
//      },
//    );
    var resbd = await res.transform(Convert.utf8.decoder).join();
    Map data = Convert.jsonDecode(resbd);
    setState(() {
      subjects = data['subjects'];
      print('${subjects.length}');
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    requestInfo();
  }

  @override
  Widget build(BuildContext context) {
    if (subjects.length == 0) {
      return Center(child: CupertinoActivityIndicator());
    }
    return ListView.builder(
        itemCount: subjects.length,
        itemBuilder: (context, index) {
          return Column(
            children: <Widget>[
              //电影主介绍
              Container(
                width: double.infinity,
                child: getMovieInfo(subjects[index], index),
              ),
              //描述
//              Container(
//                child: Column(
//                  children: getBrief(subjects[index]),
//                ),
//              ),
              //灰色横杠
              Container(
                height: 10,
                color: Color(0xFFeeeeee),
              )
            ],
          );
        });
  }

  Widget getMovieInfo(var subject, var index) {
    return Row(
      children: <Widget>[
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              constraints: BoxConstraints.loose(Size(60, 23)),
              margin: EdgeInsets.fromLTRB(25, 0, 10, 10),
              child: Center(
                  child: Text(
                'No.${index + 1}',
                style: TextStyle(color: Color(0xFF99671e)),
              )),
              decoration: BoxDecoration(
                  color: Color(0xFFf5c87e),
                  borderRadius: BorderRadius.all(Radius.circular(3)),
                  boxShadow: [
                    BoxShadow(
                        color: Color(0xFF828282),
                        offset: Offset(1.1, 1.0),
                        blurRadius: 1.8,
                        spreadRadius: 0.3)
                  ]),
            ),
            Container(
              margin: EdgeInsets.fromLTRB(25, 0, 10, 7),
              decoration: BoxDecoration(
                  boxShadow: [
                    BoxShadow(
                        color: Color(0xFF828282),
                        offset: Offset(1.0, 1.8),
                        blurRadius: 1,
                        spreadRadius: 0.3)
                  ],
                  image: DecorationImage(
                      image: NetworkImage(subject['images']['medium']),
                      fit: BoxFit.cover),
                  borderRadius: BorderRadius.all(Radius.circular(4))),
              height: 100,
              width: 75,
              alignment: Alignment.topLeft,
            )
          ],
        ),
        Container(
          alignment: Alignment.topLeft,
          height: 180,
          width: 170,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                height: 50,
              ),
              Wrap(
                crossAxisAlignment: WrapCrossAlignment.center,
                alignment: WrapAlignment.center,
                children: <Widget>[
                  Icon(Icons.play_circle_outline, color: Colors.red),
                  Text(
                    subject['title'],
                    style: TextStyle(
                        color: Colors.black,
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        height: 1.3),
                    softWrap: true,
                    overflow: TextOverflow.ellipsis,
                  ),
                  Text(
                    " (${subject['year']})",
                    style: TextStyle(height: 1.37),
                  )
                ],
              ),
              Container(
                height: 3,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: getStars(subject['rating']['average']),
              ),
              Container(
                height: 3,
              ),
              getOtherInfo(subject['genres']),
              getCasts(subject['casts']),
            ],
          ),
        ),
        LikeButton(
          widget.key,
          name: subject['title'],
          set: likedSet,
          onChanged: (set) {
            setState(() {
              if (set.contains(subject['title']))
                set.remove(subject['title']);
              else
                set.add(subject['title']);
              likedSet = set;
            });
          },
        )
      ],
    );
  }

  //小星星和评分
  List<Widget> getStars(var score) {
    List<Widget> stars = [];
    var star = score / 2;
    //判断小星星
    for (int i = 0; i < 5; i++) {
      var choice = star;
      if (choice >= 1)
        stars.add(Icon(
          Icons.star,
          size: 14,
          color: Color(0xFFf2b14a),
        ));
      if (choice < 1 && choice >= 0.5)
        stars.add(
          Icon(
            Icons.star_half,
            size: 14,
            color: Color(0xFFf2b14a),
          ),
        );
      if (choice < 0.5)
        stars.add(Icon(
          Icons.star_border,
          size: 14,
          color: Color(0xFFf2b14a),
        ));
      star--;
    }
    //添加分数
    stars.add(Text(
      ' $score',
      style: TextStyle(fontSize: 13),
    ));
    return stars;
  }

  //获取其他数据
  Widget getOtherInfo(var info) {
    var genresList = [];
    for (int i = 0; i < info.length; i++) {
      genresList.add(info[i]);
    }
    return Container(
        child: Text(
      genresList.join(' '),
      softWrap: true,
    ));
  }

  //获取演员的数据
  Widget getCasts(var casts) {
    var castList = [];
    for (int i = 0; i < casts.length; i++) {
      castList.add(casts[i]['name']);
    }
    return Container(child: Text(castList.join('/'), softWrap: true));
  }

//  List<Widget> getBrief(var subject) {
//    List<Widget> dates = [];
//    for (int i = 0; i < subject['pubdates'].length; i++) {
//      dates.add(Container(
//          child: Expanded(child: Text(subject['pubdates'][i]))));
//    }
//    return dates;
//  }
}

class LikeButton extends StatelessWidget {
  final Set set;

  final String name;

  final ValueChanged<Set> onChanged;

  LikeButton(Key key, {this.set, this.name, this.onChanged}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
          border: Border(
              left: BorderSide(style: BorderStyle.solid, color: Colors.grey))),
      padding: EdgeInsets.all(12),
      margin: EdgeInsets.only(left: 12),
      child: InkWell(
        borderRadius: BorderRadius.circular(5),
        onTap: () {
          onChanged(set);
        },
        child: Column(
          children: <Widget>[
            Icon(
              set.contains(name) ? Icons.favorite : Icons.favorite_border,
              color: Colors.red,
            ),
            Text(
              '想看',
              softWrap: true,
              style: TextStyle(color: Colors.red),
              overflow: TextOverflow.ellipsis,
            )
          ],
        ),
      ),
    );
  }
}
